package serial_cli

import (
	"fmt"
	"github.com/ilyakaznacheev/cleanenv"
)

type SerialConfig struct {
	// Device path (/dev/ttyS0)
	Name string `env:"NAME" env-default:"/dev/ttyS0" `

	// Baud rate
	BaudRate uint32 `env:"BAUD_RATE" env-default:"9600" `

	// Total timeout
	ReadTimeout uint32 `env:"READ_TIMEOUT" env-default:"5000" `

	// Size is the number of data bits. If 0, DefaultSize is used.
	// Data bits: 5, 6, 7 or 8 (default 8)
	DataBits byte `env:"DATA_BITS" env-default:"8" `

	// Parity is the bit to use and defaults to ParityNone (no parity bit).
	Parity string `env:"PARITY" env-default:"N" `

	// Number of stop bits to use. Default is 1 (1 stop bit).
	StopBits byte `env:"STOP_BITS" env-default:"1" `

	//Enable RTS/CTS (hardware) flow control.
	RTSCTSFlowControl bool `env:"RTSCTS_FLOW_CONTROL" env-default:"false" `

	RS485 RS485Config

	// DTRFlowControl bool
	// XONFlowControl bool

	// CRLFTranslate bool
}

type RS485Config struct {
	// Enable RS485 support
	Enabled bool `env:"RS485_ENABLE" env-default:"false" `
	// Delay RTS prior to send time.Duration
	DelayRtsBeforeSend uint32 `env:"RS485_DELAY_RTS_BEFORE_SEND"  `
	// Delay RTS after send time.Duration
	DelayRtsAfterSend uint32 `env:"RS485_DELAY_RTS_AFTER_SEND"  `
	// Set RTS high during send
	RtsHighDuringSend bool `env:"RS485_RTS_HIGH_DURING_SEND"  `
	// Set RTS high after send
	RtsHighAfterSend bool `env:"RS485_RTS_HIGH_AFTER_SEND"  `
	// Rx during Tx
	RxDuringTx bool `env:"RS485_RX_DURING_TX"  `
}

func loadConfig() *SerialConfig {

	//环境加载
	serialConfig := SerialConfig{}
	err := cleanenv.ReadConfig("serial-cli.env", &serialConfig)
	if err != nil {
		fmt.Println("无法加载 serial-cli.env")
		err = nil
	}
	_ = cleanenv.ReadEnv(&serialConfig)
	return &serialConfig
}
